package com.meilele.controller.hongdian;

import com.meilele.biz.hongdian.ThiCaseBiz;
import com.meilele.biz.hongdian.ThiCaseLableBiz;
import com.meilele.biz.hongdian.ThiCaseManagerBiz;
import com.meilele.entity.hongdian.*;
import com.meilele.entity.zhengchao.AjaxMsgModel;
import com.meilele.util.zhengchao.Contants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/manager")
public class ThiCaseManagerController {

    @Resource
    private ThiCaseManagerBiz managerBiz;
    @Resource
    private ThiCaseBiz caseBiz;
    @Resource
    private ThiCaseLableBiz caseLableBiz;

    @RequestMapping("/index")
    public String index(){
        return "/third/manager/index";
    }

    @RequestMapping("/list")
    public String list(Model model , int pageNum){
        int totalCount = caseBiz.findCount();
        List<ThiCase> caseManagerList = managerBiz.findAllCaseManager(pageNum);
        for (ThiCase thiCase : caseManagerList){
            Date date = thiCase.getCreateTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String stringDate = format.format(date);
            thiCase.setStringDate(stringDate);
        }
        model.addAttribute("caseManagerList",caseManagerList);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageNum",pageNum);
        return "/third/manager/list";
    }


    @RequestMapping("preAdd")
    public String preAdd(Model model, ThiCase thiCase){
        List<ThiCaseLable> caseLableList = caseLableBiz.findSingleLable();
        model.addAttribute("caseLableList",caseLableList);

        List<ThiCaseBigType> bigTypeList = caseLableBiz.findAllStyle();
        model.addAttribute("bigTypeList",bigTypeList);

//        managerBiz.saveCase(thiCase);
        return "/third/manager/add";
    }

//    , MultipartHttpServletRequest request
//    ThiCase thiCase, @RequestParam("lableId") int [] ids,ThiShow thiShow,
//ThiLables lables , @RequestParam("fileName")CommonsMultipartFile [] files
    @ResponseBody
    @RequestMapping("/add")
    public AjaxMsgModel add(ThiCase thiCase, MultipartHttpServletRequest request,
                      @RequestParam("lableId") int [] ids, ThiShow thiShow,
                      ThiLables lables , @RequestParam("fileName")CommonsMultipartFile [] files) throws IOException {
        //案例添加
        Date date = new Date();
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String stringDate = format.format(date);
        thiCase.setCreateTime(date);

        MultipartFile logoFile = request.getFile("photo1");
        MultipartFile caseFile = request.getFile("photo2");
        String logoFileName = UUID.randomUUID().toString();
        String caseFileName = UUID.randomUUID().toString();
        File newLogoFile = new File(Contants.IMAGE_PATH + logoFileName);
        File newCaseFile = new File(Contants.IMAGE_PATH + caseFileName);
        logoFile.transferTo(newLogoFile);
        caseFile.transferTo(newCaseFile);
        thiCase.setCaseImage(logoFile.getOriginalFilename());
        thiCase.setCaseBigImage(caseFile.getOriginalFilename());

        //添加案例
        int pictureNum = files.length;
        thiCase.setCasePicture(pictureNum);

        //添加show表中的数据
        MultipartFile showFile = request.getFile("photo3");
        String showFileName = UUID.randomUUID().toString();
        File newShowFile = new File(Contants.IMAGE_PATH + showFileName);
        showFile.transferTo(newShowFile);
        thiShow.setShowImage(showFile.getOriginalFilename());
        thiShow.setShowLogo(thiCase.getCaseImage());
        thiShow.setShowCompany(thiCase.getCaseCompany());
        thiShow.setShowDesc(thiCase.getCaseDesc());
        //遍历每次选中的标签id
        for (int id : ids){
            if (id <= 16 && id > 0){
                thiShow.setShowStyle(managerBiz.findLableById(id).getCaseLable());
            }else if (id <= 26){
                thiShow.setShowCity(managerBiz.findLableById(id).getCaseLable());
            }else if (id <= 32){
                thiShow.setShowRoom(managerBiz.findLableById(id).getCaseLable());
            }else if (id <= 40){
                int lastZero = managerBiz.findLableById(id).getCaseLable().lastIndexOf("0");
                thiShow.setShowArea(Integer.parseInt(managerBiz.findLableById(id).getCaseLable().substring(0,lastZero)));
            }else {
                thiShow.setShowPrice(managerBiz.findLableById(id).getCaseLable());
            }
        }
        managerBiz.insertSelective(thiShow);

        //图片添加表
        for (MultipartFile file : files){
            String fileName = UUID.randomUUID().toString();
            File newFile = new File(Contants.IMAGE_PATH + fileName);
            file.transferTo(newFile);
            ThiImages images = new ThiImages();
            images.setImageName(fileName);
            images.setImageImg(file.getOriginalFilename());
            //为了取出图片描述，即取出100.jpg中的100
            int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
            String imageDesc = file.getOriginalFilename().substring(0,lastIndexOf);
            images.setImageDesc(imageDesc);
            //想要获取到自动递增的id，需要在ThiShowMapper.xml的insertSelective的方法中的配置
            //  useGeneratedKeys="true" keyProperty="showId"
            images.setShowId(thiShow.getShowId());
            managerBiz.insertSelective(images);
        }
        thiCase.setShowId(thiShow.getShowId());
        caseBiz.insertSelective(thiCase);


        //标签添加
        for (int id : ids){
            lables.setLableId(id);
            //想要获取到自动递增的id，需要在ThiCaseMapper.xml的insertSelective的方法中的配置
            //  useGeneratedKeys="true" keyProperty="caseId"
            lables.setCaseId(thiCase.getCaseId());
            //添加中间表的多个id
            managerBiz.insertSelective(lables);
        }

        return new AjaxMsgModel("200","添加成功","hdlist","","closeCurrent","");

    }


    @RequestMapping("/preUpdate")
    public String preUpdate(Model model ,int caseId){
        //根据id查询出的案例对象
        ThiCase thiCase = managerBiz.findCaseById(caseId);
        model.addAttribute("thiCase",thiCase);

        //查询出标签的五大类
        List<ThiCaseBigType> bigTypeList = caseLableBiz.findAllStyle();
        model.addAttribute("bigTypeList",bigTypeList);

        //案例标签集合
        List<ThiCaseLable> caseLableList = caseLableBiz.findAllCaseLable();
        model.addAttribute("caseLableList",caseLableList);

//        List<ThiCaseLable> caseLableArrayList = new ArrayList<>();
        List<Integer> caseLableArrayList = new ArrayList<>();
        List<ThiLables> lablesListId = managerBiz.findLablesId(caseId);
        for (ThiLables lablesId : lablesListId){
            ThiCaseLable caseLable = new ThiCaseLable();
            ThiCaseLable thiCaseLable = managerBiz.findLablesById(lablesId.getLableId());
            caseLable.setLableId(thiCaseLable.getLableId());
            caseLableArrayList.add(caseLable.getLableId());
        }
        model.addAttribute("caseLableArrayList",caseLableArrayList);

        ThiShow thiShow = managerBiz.findShowById(thiCase.getShowId());
        model.addAttribute("thiShow",thiShow);

        return "/third/manager/update";
    }
    @ResponseBody
    @RequestMapping("/update")
    public AjaxMsgModel update(ThiCase thiCase, @RequestParam("lableId") int [] ids, ThiShow thiShow, ThiLables lables ) throws IOException {

        //案例添加
        Date date = new Date();
        thiCase.setCreateTime(date);

//        MultipartFile logoFile = request.getFile("photo1");
//        MultipartFile caseFile = request.getFile("photo2");
//        String logoFileName = UUID.randomUUID().toString();
//        String caseFileName = UUID.randomUUID().toString();
//        File newLogoFile = new File(Constant.IMAGE_PATH + logoFileName);
//        File newCaseFile = new File(Constant.IMAGE_PATH + caseFileName);
//        logoFile.transferTo(newLogoFile);
//        caseFile.transferTo(newCaseFile);
//        thiCase.setCaseImage(logoFile.getOriginalFilename());
//        thiCase.setCaseBigImage(caseFile.getOriginalFilename());

        //添加案例
//        int pictureNum = files.length;
//        thiCase.setCasePicture(pictureNum);
        managerBiz.updateByPrimaryKeySelective(thiCase);

        //添加show表中的数据
//        MultipartFile showFile = request.getFile("photo3");
//        String showFileName = UUID.randomUUID().toString();
//        File newShowFile = new File(Constant.IMAGE_PATH + showFileName);
//        showFile.transferTo(newShowFile);
//        thiShow.setShowImage(showFile.getOriginalFilename());
//        thiShow.setShowLogo(thiCase.getCaseImage());
        thiShow.setShowCompany(thiCase.getCaseCompany());
        thiShow.setShowDesc(thiCase.getCaseDesc());
        //遍历每次选中的标签id
        for (int id : ids){
            if (id <= 16 && id > 0){
                thiShow.setShowStyle(managerBiz.findLableById(id).getCaseLable());
            }else if (id <= 26){
                thiShow.setShowCity(managerBiz.findLableById(id).getCaseLable());
            }else if (id <= 32){
                thiShow.setShowRoom(managerBiz.findLableById(id).getCaseLable());
            }else if (id <= 40){
                int lastZero = managerBiz.findLableById(id).getCaseLable().lastIndexOf("0");
                thiShow.setShowArea(Integer.parseInt(managerBiz.findLableById(id).getCaseLable().substring(0,lastZero)));
            }else {
                thiShow.setShowPrice(managerBiz.findLableById(id).getCaseLable());
            }
        }
        managerBiz.updateByPrimaryKeySelective(thiShow);


        //图片添加表
//        for (MultipartFile file : files){
//            String fileName = UUID.randomUUID().toString();
//            File newFile = new File(Constant.IMAGE_PATH + fileName);
//            file.transferTo(newFile);
//            ThiImages images = new ThiImages();
//            images.setImageName(fileName);
//            images.setImageImg(file.getOriginalFilename());
//            //为了取出图片描述，即取出100.jpg中的100
//            int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
//            String imageDesc = file.getOriginalFilename().substring(0,lastIndexOf);
//            images.setImageDesc(imageDesc);
//            //想要获取到自动递增的id，需要在ThiShowMapper.xml的insertSelective的方法中的配置
//            //  useGeneratedKeys="true" keyProperty="showId"
//            images.setShowId(thiShow.getShowId());
//            managerBiz.updateImages(thiShow.getShowId());
//        }

//        thiCase.setShowId(thiShow.getShowId());
//        managerBiz.updateCase(thiCase.getCaseId());
//        caseBiz.insertSelective(thiCase);


        //中间表添加外键关联的id的时候，进行先删再加
        managerBiz.deleteLables(thiCase.getCaseId());
        //标签添加
        for (int id : ids){
            lables.setLableId(id);
            //想要获取到自动递增的id，需要在ThiCaseMapper.xml的insertSelective的方法中的配置
            //  useGeneratedKeys="true" keyProperty="caseId"
            lables.setCaseId(thiCase.getCaseId());
            //添加中间表的多个id
            managerBiz.insertSelective(lables);
        }

        return new AjaxMsgModel("200","添加成功","hdlist","","closeCurrent","");

    }

    @ResponseBody
    @RequestMapping("delete")
    public AjaxMsgModel delete(int caseId){
        //根据caseId查询出需要删除的某一个对象
        ThiCase thiCase = managerBiz.findCaseById(caseId);
        //根据caseId删除中间表thi_Lable中对应的lableId
        managerBiz.deleteLables(caseId);
        //获取案例表中的showId
        int showId = thiCase.getShowId();
        //根据showId删除展示表（thi_show）中的数据
        managerBiz.deleteShow(showId);
        //根据showId删除展示表（thi_images）中的数据
        managerBiz.deleteImages(showId);
        //根据caseId删除案例表中的数据
        managerBiz.deleteCase(caseId);
        return new AjaxMsgModel("200","添加成功","hdlist","","closeCurrent","");

    }
}
